<template>
  <view>
    <text class="sms_label" v-if="!count_down" @click="resend">获取验证码</text>
    <text class="sms_label_djs" v-else>重新发送({{ count_down }}秒)</text>
  </view>
</template>

<script>
const api = require('@/utils/request.js');
export default {
  props: {
    totalSeconds: {
      type: Number,
      default: 60
    },
    disabled: {
      type: Boolean,
      default: false
    },
    phoneNumber: {
      type: Number,
      required: true,
      default: 0
    }
  },
  data() {
    return {
      regex: /^1[3-9]\d{9}$/,
      count_down: '',
      timer: null
    };
  },
  methods: {
    countdown() {
      this.timer = setInterval(() => {
        this.count_down = this.count_down - 1;
        if (this.count_down < 10) {
          this.count_down = '0' + this.count_down;
        }
        if (this.count_down <= 0) {
          clearInterval(this.timer);
          this.count_down = '';
        }
      }, 1000);
    },
    clearTimer() {
      clearInterval(this.timer);
      this.timer = null;
    },
    async resend() {
      if (this.regex.test(this.phoneNumber)) {
        this.count_down = this.totalSeconds;
        this.countdown();
        const res = await api.request({ url: '/sms/sendVerificationCode', data: { phoneNumber: this.phoneNumber }, method: 'GET' });
        if (res.code === 200) {
          this.$emit('resend', res.data);
        } else if (res.code === 500 && res.msg === '您获取短信次数过于频繁，请稍后再试') {
          uni.showToast({ title: res.msg, icon: 'none', duration: 2000 });
        } else {
          uni.showToast({ title: res.msg, icon: 'error', duration: 1500 });
        }
      }
    }
  },
  onLoad() {
    this.countdown();
  },
  onUnload() {
    this.clearTimer();
  },
  onHide() {
    this.clearTimer();
  }
};
</script>

<style lang="scss" scoped>
.sms_label {
  display: block;
  width: 96rem;
  text-align: right;
  font-size: 14rem;
  font-weight: 400;
  color: rgba(56, 56, 56, 1) !important;
}
.sms_label_djs {
  display: block;
  width: 102rem;
  text-align: right;
  font-size: 14rem;
  font-weight: 400;
}
</style>
